package no.cicero.testframework.xml.testcase;

import no.cicero.testframework.common.xml.XmlImporter;
import no.cicero.testframework.common.xml.XmlImporterDelegateBase;
import no.cicero.testframework.common.xml.XmlTag;
import no.cicero.testframework.model.testcase.ClientObject;
import org.xml.sax.SAXException;

public class ClientObjectImporter extends XmlImporterDelegateBase {
    private static int ROOT_STATE = 12345;

    private Integer oldState = null;
    private ClientObjectImporter delegate = null;
    
    private ClientObject clientObject = null;
    ClientObject getClientObject() { return clientObject; }

    private String value = null;
    String getValue() { return value; }

    //----interface IXmlImporterDelegate
    @Override
    public void handleStartElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if(oldState == null){
            oldState = tag.getState();
            tag.setState(ROOT_STATE);
            clientObject = new ClientObject();
        } else {
            value = null;
            delegate = new ClientObjectImporter();
            importer.pushDelegate(delegate);
        }
    }

    @Override
    public void handleEndElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if(tag.getState() == ROOT_STATE){
            tag.setState(oldState);
            oldState = null;
        } else if(delegate != null) {
            if(delegate.getValue() != null){
                clientObject.addField(tag.getName(), delegate.getValue());
            } else {
                clientObject.addField(tag.getName(), delegate.getClientObject());
            }
            delegate = null;
        }
    }

    @Override
    public void handleText(XmlImporter importer, XmlTag tag, String text) throws SAXException {
        if(delegate == null) {
            value = text;
        }
    }


}
